package com.hwtx.form.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URL;
import java.util.*;

@Slf4j
public class ResourceLoader {

    public interface LoadedCallback<T> {
        void call(T object);
    }

    public static <T> void load(Class<T> clazz, LoadedCallback<T> callback) {
        ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
        for (T object : serviceLoader) {
            if (callback != null) {
                callback.call(object);
            }
        }
    }

    public static <T> List<T> load(Class<T> clazz) {
        ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
        if (!serviceLoader.iterator().hasNext()) {
            return Lists.newArrayList();
        }
        List<T> ret = new ArrayList<>();
        for (T t : serviceLoader) {
            ret.add(t);
        }
        return ret;
    }

    public static Map<String, String> getClasspathPropertiesInfo(String file) {
        Map<String, String> ret = Maps.newHashMap();
        List<URL> urls = getClassPathResources(file);
        urls.forEach(url -> {
            try {
                Properties properties = new Properties();
                properties.load(url.openStream());
                properties.keySet().forEach(key -> {
                    if (ret.containsKey((String) key)) {
                        log.error("已包含属性名{}，path = {}", key, url);
                    }
                    ret.put((String) key, (String) properties.get(key));
                });
            } catch (IOException e) {
                log.error("", e);
            }
        });
        return ret;
    }

    private static List<URL> getClassPathResources(String file) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        List<URL> urls = Lists.newArrayList();
        try {
            Enumeration<URL> resources = classLoader.getResources(file);
            while (resources.hasMoreElements()) {
                urls.add(resources.nextElement());
            }
        } catch (IOException e) {
            log.error("", e);
        }
        return urls;
    }
}
